package com.jspx.txweb.dispatcher.handle;

import com.jspx.boot.sign.HttpStatusType;
import com.jspx.txweb.ActionInvocation;
import com.jspx.txweb.config.ActionConfig;
import com.jspx.txweb.dispatcher.Dispatcher;
import com.jspx.txweb.dispatcher.WebHandle;
import com.jspx.txweb.env.TXWeb;
import com.jspx.txweb.proxy.DefaultActionInvocation;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.txweb.util.TXWebUtil;
import com.jspx.utils.StringUtil;
import com.jspx.utils.URLUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/17.
 * 默认的模版执行
 */
public class ActionHandle extends WebHandle {
    final public static  String  name = "action";

    Map<String, Object> createEnvironment(final HttpServletRequest request,final HttpServletResponse response) throws Exception {
        namePart = URLUtil.getFileNamePart(request.getServletPath());
        namespace = TXWebUtil.getNamespace(request.getServletPath());
        if (!StringUtil.hasLength(namespace)) namespace = TXWeb.global;
        if (!StringUtil.hasLength(namePart)|| "/".equals(namePart)) namePart = "index";
        ////////////////////action begin

        //////////////////////////////////环境参数 begin
        Map<String, Object> envParams = TXWebUtil.createEnvironment();
        envParams.put(ActionSupport.Key_ActionName, namePart);
        envParams.put(ActionSupport.Key_Namespace, namespace);
        envParams.put(ActionSupport.Key_RealPath, Dispatcher.getRealPath());
        envParams.put(ActionSupport.Key_Request, request);
        envParams.put(ActionSupport.Key_Response, response);
        ///////////////////////////////////环境参数 end

        actionConfig = webConfigManager.getActionConfig(namePart, namespace, true);
        return envParams;
    }

    @Override
    public void doing(final HttpServletRequest request,final HttpServletResponse response) throws Exception {
        //////////////////////////////////环境参数 begin
        Map<String, Object> envParams = createEnvironment( request, response);
        if (actionConfig == null)
        {
            //TXWebUtil.errorPrint("not found,找不到文件",response, HttpStatusType.HTTP_status_404);
            log.debug("actionConfig  is NULL namePart=" + namePart + "  namespace=" + namespace);
            throw  new Exception("actionConfig  is NULL namePart=" + namePart + "  namespace=" + namespace);
        }
        ActionInvocation actionInvocation = new DefaultActionInvocation(actionConfig, envParams,null, request, response);
        actionInvocation.initAction();
        actionInvocation.invoke();
        actionInvocation.executeResult(null);
        ////////////////////action end
    }



}
